<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProductAttr;
use App\Models\ProductAttrResult;
use App\Models\ProductAttrValue;
use App\Models\StoreCombination;
use App\Traits\Controllers\AdminTraits;
use App\Transformers\Store\StoreCombinationTransformer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StoreCombinationsController extends Controller
{
    use AdminTraits;

    public $model = StoreCombination::class;

    public $transformer = StoreCombinationTransformer::class;

    /**
     * 参数验证规则
     *
     * @param Request $request
     * @return array
     */
    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'GET':
                return [];
                break;
            case 'PUT':
            case 'POST':
                return [
                    'recommend_image' => 'required|max:255',
                    'product_id' => 'required|numeric',
                    'rotation_chart' => 'required|array',
                    'title' => 'required|max:255',
                    'introduce' => 'required|max:255',
                    'description' => 'required|max:255',
                    'start_at' => 'required',
                    'stop_at' => 'required',
                    'unit_name' => 'required|max:10',
                    'order_effective_at' => 'required|max:10',
                    'people' => 'required|max:10',
                    'num' => 'required|max:10',
                    'quota' => 'required|max:10',
                    'temp_id' => 'required',
                    'merchant_id' => 'required',
                    'attr_v' => 'required|array',
                ];
                break;
            case 'PATCH':
                return [];
                break;
        }
        return [];
    }

    /**
     * 验证信息
     *
     * @return array
     */
    public function ruleMessages(): array
    {
        return [
            'recommend_image.required' => '主图不能为空',
            'product_id.required' => '商品ID不能为空',
            'rotation_chart.required' => '轮播图不能为空',
            'title.required' => '拼团名称不能为空',
            'introduce.required' => '简介不能为空',
            'description.required' => '内容不能为空',
            'start_at.required' => '开始时间不能为空',
            'stop_at.required' => '结束时间不能为空',
            'unit_name.required' => '单位不能为空',
            'order_effective_at.required' => '拼团时效不能为空',
            'people.required' => '拼团人数不能为空',
            'num.required' => '单次购买数量限制不能为空',
            'quota.required' => '总购买数量限制不能为空',
            'quota_show.required' => '限量不能为空',
            'quota_show.not_in' => '限量必须大于零',
            'quota_show.array' => '限量必须为数组',
            'price.required' => '拼团价格不能为空',
            'price.array' => '拼团价格必须为数组',
            'temp_id.required' => '运费模板不能为空',
            'merchant_id.required' => '商户ID不能为空',
            'attr_v.required' => '规格值必填',
            'attr_v.array' => '规格值必须为数组',

        ];
    }

    /**
     * 添加拼团商品
     * @param Request $request
     */
    public function store(Request $request)
    {

        $this->validateData($request);
        //判断如果没传商品ID 返回错误信息请选择商品信息
        $request->offsetSet('system_admin_id', $this->admin_user('id'));
        //判断如果开始时间比当前时间要早则不能添加
        if ($request->start_at < date('Y-m-d H:i:s')) return $this->response->errorBadRequest('时间比当前时间早');

        try {
            DB::beginTransaction();//开启事务
            //然后遍历规格数据拿到值
            foreach ($request->attr_v as $k => $v) {
                $attr_result[$k]['product_id'] = $request->product_id;
                $attr_result[$k]['result'] = json_encode($request->attr_v[$k]);
                $attr_result[$k]['type'] = 'combination';
                $attr_result[$k]['created_at'] = date('Y-m-d H:i:s');
                $attr_result[$k]['updated_at'] = date('Y-m-d H:i:s');
                $quota[$k] = $v['value'][0]['quota'];//获取规格的限量
                $price[$k] = $v['value'][0]['price'];//获取规格的价格
                $cost_price = $v['value'][0]['cost'];//获取规格成本价
                $stock = $v['value'][0]['stock'];//获取规格的库存
                $weight = $v['value'][0]['weight'];//获取规格的体重
                $volume = $v['value'][0]['volume'];//获取规格体积
            }

            //判断拼团价格和限量不能为空或为0
            foreach ($price as $k => $v) {
                if ($price[$k] == 0 || null && $quota[$k] == 0 || null) {
                    return $this->response->errorBadRequest('拼团金额和限量 不能为空 或者为零');
                }
            }

            //2.把砍价价格和限量追加$request验证中,把数据也添加到本表中
            request()->offsetSet('price', $price[0]);//request 追加价格字段
            request()->offsetSet('quota_show', array_sum($quota));//request 追加限量字段
            request()->offsetSet('cost_price', $cost_price);//request 追加成本价字段
            request()->offsetSet('stock', $stock);//request 追加库存字段
            request()->offsetSet('weight', $weight);//request 追加体重字段
            request()->offsetSet('volume', $volume);//request 追加体积字段

            //然后添加砍价规格的信息
            $this->getQuery()->attrResult()->insert($attr_result);
            $model = $this->getQuery()->fill($request->all());
            $model->save();

            DB::commit();//提交事务
        } catch (\Exception $e) {
            DB::rollBack();//回滚事务
            report($e);
        }

        //进行批量赋值
        return $this->response->created();
    }

    /**
     * 拼团详情
     */
    public function show($id)
    {
        $show = $this->getQuery()->findOrFail($id);// findOrFail 查找失败时抛出异常404
        $show_r = $show->attrResult()->where('created_at', $show->created_at)->select('result')->where('type', 'combination')->get();
        $show->att_r = $show_r;
        if ($this->policy) {
            $this->authorize('show', $show);
            // authorize 控制器授权  当你尝试授权一个动作并且在用户不允许执行给定动作时抛出授权异常
            //那么使用authorize()方法，会在异常时返回一个异常403响应错误。
        }
        return $this->response->item($show, resolve($this->transformer));
    }

    /**
     *拼团修改
     */
    public function update($id, Request $request)
    {

        $this->validateData($request);
        //判断如果没传商品ID 返回错误信息请选择商品信息
        $request->offsetSet('system_admin_id', $this->admin_user('id'));

        try {

            DB::beginTransaction();//开启事务

            $data = $this->getQuery()->findOrFail($id);
            $time = Carbon::parse($data['created_at'])->toDateTimeString();//转换时间格式
            if ($request->start_at < date('Y-m-d H:i:s')) return $this->response->errorBadRequest('时间比当前时间早');

            //然后遍历规格数据拿到值
            foreach ($request->attr_v as $k => $v) {
                $attr_result[$k]['product_id'] = $request->product_id;
                $attr_result[$k]['result'] = json_encode($request->attr_v[$k]);
                $attr_result[$k]['type'] = 'combination';
                $attr_result[$k]['created_at'] = $time;
                $attr_result[$k]['updated_at'] = $time;
                $quota[$k] = $v['value'][0]['quota'];//获取规格的限量
                $price[$k] = $v['value'][0]['price'];//获取规格的价格
                $cost_price = $v['value'][0]['cost'];//获取规格成本价
                $stock = $v['value'][0]['stock'];//获取规格的库存
                $weight = $v['value'][0]['weight'];//获取规格的体重
                $volume = $v['value'][0]['volume'];//获取规格体积
            }

            //判断拼团价格和限量不能为空或为0
            foreach ($price as $k => $v) {
                if ($price[$k] == 0 || null && $quota[$k] == 0 || null) {
                    return $this->response->errorBadRequest('拼团金额和限量 不能为空 或者为零');
                }
            }

            //2.把拼团价格和限量追加$request验证中,把数据也添加到本表中
            request()->offsetSet('price', $price[0]);//request 追加价格字段
            request()->offsetSet('quota_show', array_sum($quota));//request 追加限量字段
            request()->offsetSet('cost_price', $cost_price);//request 追加成本价字段
            request()->offsetSet('stock', $stock);//request 追加库存字段
            request()->offsetSet('weight', $weight);//request 追加体重字段
            request()->offsetSet('volume', $volume);//request 追加体积字段

            ProductAttrResult::where('created_at', $time)->where('type', 'combination')->delete();

            //然后更新砍价规格的信息
            $this->getQuery()->attrResult()->insert($attr_result);

            if ($this->policy) {
                $this->authorize('update', $data);
            }

            $data->fill($request->all());
            $data->save();

            DB::commit();//提交事务
        } catch (\Exception $e) {
            DB::rollBack();//回滚事务
            report($e);
        }

        //进行批量赋值
        return $this->response->noContent();

    }

    /**
     * 删除拼团商品
     */
    public function destroy($id)
    {
        $ids = array_filter(explode(',', $id));
        if (empty($ids)) {
            return $this->response->errorBadRequest();
        }
        $data = $this->getQuery()->where('id', $id)->first();
        $data->attrResult()->where('created_at', $data->created_at)->where('type', 'combination')->delete();
        $this->getQuery()->whereIn($this->getQuery()->getKeyName(), $ids)->delete();
        return $this->response->noContent();
    }

    /**
     * 是否上架
     */
    public function status(StoreCombination $storeCombination)
    {
        $storeCombination->status = $storeCombination->status == 0 ? 1 : 0;
        $storeCombination->save();
        $this->response->noContent();
    }
}
